/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "kresourcesfiles.h"
#include "kdata.h"
#include "kerror.h"
#include "kstdiostream.h"

#include <fstream>

kResourcesFiles::kResourcesFiles(const std::tstring& rootPath) {
	_rootPath = rootPath;
}

kStream* kResourcesFiles::doOpen(const std::tstring& uri) {
	std::fstream* fs = new std::fstream((_rootPath + uri).c_str(), std::ios::in | std::ios::binary);
	return new kStdioStream((std::istream*)fs, [=] { delete fs; });
}
void kResourcesFiles::doClose(kStream* stream) {
	delete stream;
}
void kResourcesFiles::doUpdate(const std::tstring& uri, kStream* stream) {
	std::ofstream f((_rootPath + uri).c_str(), std::ios::out | std::ios::binary);
	
	uint8_t buffer[256];
	while (stream->tell(keSeek_Read) + sizeof(buffer) < stream->getSize()) {
		stream->read(buffer);
		f.write((const char*)buffer, sizeof(buffer));
	}

	size_t size = stream->getSize() - stream->tell(keSeek_Read);
	stream->read(kData(buffer, size));
	f.write((const char*)buffer, size);

	f.close();
}
